package jpavlich.cardsorter.action;

import java.util.HashMap;
import java.util.Map;

public class ResourceManager {
	public static final ResourceManager INSTANCE = new ResourceManager();
	private Map<String, Object> resources = new HashMap<String, Object>();
	private Map<Object, String> invResources = new HashMap<Object, String>();
	private Map<Class<?>, Long> objCounter = new HashMap<Class<?>, Long>();

	private ResourceManager() {
		
	}
	
	public void registerResource(Object res) {
		if (!invResources.containsKey(res)) {
			String newID = getNewId(res);
			resources.put(newID, res);
			invResources.put(res, newID);
		}
	}
	
	public Object findResource(Class<?> type, long count) {
		return findResource(buildID(type,count));
	}
	
	public Object findResource(String resId) {
		return resources.get(resId);
	}
	
	public String getResourceID(Object res) {
		return invResources.get(res);
	}

	private String getNewId(Object res) {
		Long count = objCounter.get(res.getClass());
		if (count == null) {
			count = 0l;
		} else {
			count++;
		}
		objCounter.put(res.getClass(), count);
		return buildID(res.getClass(), count);
	}

	private String buildID(Class<?> type, long count) {
		return type.getCanonicalName() + "_" + count;
	}
}
